import * as types from '../constants/ActionTypes'
import * as API_RIGHTMENU from '../apis/customerRightMenu'
import * as Actions from '../actions/viewCustomerBase'

import { Modal,message } from 'antd'
const confirm = Modal.confirm;
import objectAssign from 'object-assign'
import { WeaTable } from 'comsRedux'
const WeaTableAction = WeaTable.action;

import { WeaTools } from 'ecCom'
import Immutable from 'immutable'

//发送邮件   key == 3
export const addMailMenu =(id)=>{
     return(dispatch, getState) => {
		API_RIGHTMENU.addMailMenu({"customerids":id}).then((data) => {
            var url = "/email/new/MailInBox.jsp?opNewEmail=1&isInternal=0&to="+data.datas;
            openFullWindowHaveBar(url); 
		});
	}
 }


window.openFullWindowHaveBar = function(params){
  openFullWindowHaveBar(params);
}

//查看
const openFullWindowHaveBar = (params)=>{
  openWindow(params);
}

const openWindow = (url)=>{
    let width = screen.availWidth-10 ;
    let height = screen.availHeight-50 ;
    let szFeatures = "top=0," ;
    szFeatures +="left=0," ;
    szFeatures +="width="+width+"," ;
    szFeatures +="height="+height+"," ;
    szFeatures +="directories=no," ;
    szFeatures +="status=yes,toolbar=no,location=no," ;
    szFeatures +="menubar=no," ;
    szFeatures +="scrollbars=yes," ;
    szFeatures +="resizable=yes" ; 
    window.open(url,"",szFeatures) ;
}

//导出客户联系
export const contactLogExport =id=>{
    return(dispatch, getState) => {
        API_RIGHTMENU.contactLogExport({"customerId":id}).then((data) => {
            window.location="/weaver/weaver.file.ExcelOut";    
		});
   }
}

//申请->成功客户   key ==10
export const urlSubmit =(url)=>{
    return(dispatch, getState) => {
        const customerId = getState().viewCustomerBase.get('customerId');
        WeaTools.callApi(url, 'GET', {}).then((data) => {
            //console.log(data)
           if(data.status=="success"){
               dispatch(Actions.initDatas({customerId:customerId}));
               message.success('操作成功！');
           }
       });
   }
}

//门户申请
var applyPortalUrl="";
export const applyPortalManager =(url)=>{
    return (dispatch,getState)=>{
        const modalInfo= {
            modalTitle:"设置密码",
            modalStyle:{width: 446, height: 240},
            modalType:"applyPortal"
        };
        applyPortalUrl = url;
        dispatch(setModalBaseInfo(modalInfo));
        dispatch(showDilog(true));
    }
}
//门户申请   密码保存
export const applyPortalSave =params=>{
    return(dispatch, getState) => {
        API_RIGHTMENU.doApply(params).then((data) => {
            if(data.status=="success"){
                dispatch(urlSubmit(applyPortalUrl));
                dispatch(Actions.initDatas({customerId:params.customerId}));
                dispatch(showDilog(false));
                dispatch(Actions.saveOrderFields({}));
            }else{
                message.error("请求失败，"+data.msgcode+"!")
            }
		});
   }
}
//修改密码
export const setPasswdSave =params=>{
    return(dispatch, getState) => {
        API_RIGHTMENU.doApply(params).then((data) => {
            if(data.status=="success"){
                dispatch(showDilog(false));
                dispatch(Actions.saveOrderFields({}));
                message.success("修改密码成功!")
            }else{
                message.error("请求失败，"+data.msgcode+"!")
            }
		});
   }
}
//控制模态框显示隐藏
export const showDilog =bool =>{
    return (dispatch,getState)=>{
        dispatch({
            type:types.VIEWCUSTOMERBASE_SHOWDIALOG,
            showModal:bool
        })
    }
}
//初始话模态框基本信息
export const setModalBaseInfo =params=>{
    return (dispatch,getState)=>{
        dispatch({
            type:types.VIEWCUSTOMERBASE_INIT_DIALOG,
            modalInfo:params
        })
    }
}

//客户合并   获取当前客户信息
export const getUniteForm =id=>{
    return(dispatch, getState) => {
        API_RIGHTMENU.getUniteForm({"customerId":id}).then((data) => {
            if(data.status=="success"){
                dispatch({type:types.VIEWCUSTOMERBASE_CUSTOMER_MERGE,customerMermgeForm:data.datas})
                let fieldsObj =crmGetFields(data.datas);
                dispatch( Actions.saveOrderFields(fieldsObj));
            }else{
                message.error("请求失败，"+data.msgcode+"!")
            }
		});
   }
}
//客户合并  保存操作
export const customerMergeSave =params=>{
    return(dispatch, getState) => {
        const orderFields = getState().viewCustomerBase.get('orderFields').toJS();
        const customerId= orderFields.customerId.value;
        const customerIds= orderFields.customerIds.value;
        if(customerId && customerIds){
            confirm({
                title: '确定要合并吗',
                content: '',
                onOk() {
                    API_RIGHTMENU.saveUniteForm({customerId:customerId,customerIds:customerIds}).then((data) => {
                        if(data.status=="success"){
                            dispatch(Actions.initDatas({customerId:customerId}));
                            dispatch(showDilog(false));
                            dispatch(Actions.saveOrderFields({}));
                            dispatch({type:types.VIEWCUSTOMERBASE_CUSTOMER_MERGE,customerMermgeForm:[]});
                        }else{
                            message.error("请求失败，"+data.msgcode+"!")
                        }
                    });
                },
                onCancel() {},
            });
        }else{
            Modal.warning({
				title: '系统提示',
				content: '必填信息不完整!',
			});
        }
   }
}

//删除
export  const deleteCustomer=id=>{
    return(dispatch, getState) => {
        API_RIGHTMENU.deleteCustomer({"customerIds":id}).then((data) => {
            if(data.status=="success"){
                window.close();
            }else{
                message.error("请求失败，"+data.msgcode+"!")
            }
		});
   }
}

//工商信息
export const getBusinessInfo =id =>{
    const modalInfo={
        modalTitle:"工商信息",
        modalStyle:{width: 830, height: 750},
        modalType:"business"
    };
    return(dispatch, getState) => {
        API_RIGHTMENU.getBusinessInfo({customerId:id}).then((data) => {
            if(data.status=="success"){
                const datas = data.datas;
                if(datas.fromCache){        //取的缓存的数据
                    dispatch({type:types.VIEWCUSTOMERBASE_SAVE_BUSINESSINFO,businessInfoData:datas.businessInfoData.data});
                    dispatch(setModalBaseInfo(modalInfo));
                    dispatch(showDilog(true));
                    API_RIGHTMENU.saveBusinessLog({customerId:id,requesttype:1}).then(data=>{   //保存日志
                        return true;
                    });
                }else{
                    let ajax = jQuery.ajax({
                        url : encodeURI(datas.url),
                        data:'{}',
                        cache : false, 
                        async : true,
                        type : "GET",
                        dataType: "jsonp",
                        timeout:1000
                    });
                    ajax.done(function(data){
                        if(data.status == "200"){
                            dispatch({type:types.VIEWCUSTOMERBASE_SAVE_BUSINESSINFO,businessInfoData:data.data});
                            dispatch(setModalBaseInfo(modalInfo));
                            dispatch(showDilog(true));
                            if(datas.isCache=="1"){   //缓存数据
                                API_RIGHTMENU.cacheBusinessInfo({customerId:id,data:JSON.stringify(data)}).then(data=>{
                                    return true;
                                })
                            };
                            API_RIGHTMENU.saveBusinessLog({customerId:id,requesttype:0}).then(data=>{    //保存日志
                                return true;
                            })
                        }else{
                            message.error("请求失败，"+data.message+"!")
                        }
                    })
                }
            }else{
                message.error("请求失败，"+data.msgcode+"!")
            }
		});
   }
}

//切换tab工商信息的
export const businessChangeTab =(key,id) =>{
    return(dispatch, getState) => {
        if(key=="2"){
             API_RIGHTMENU.getBusinessLog({"customerId":id}).then((data) => {
                if(data.status=="success"){
                   dispatch(WeaTableAction.getDatas(data.sessionkey,  1));
                   dispatch({type:types.VIEWCUSTOMERBASE_SET_BUSINESSINFO_DATAKEY,dataKey:data.sessionkey});
                }else{
                    message.error("请求失败，"+data.msgcode+"!")
                }
            });
        }
       dispatch({type:types.VIEWCUSTOMERBASE_SET_BUSINESSINFO_TAB,key:key});
   }
}

//